package com.vectquant.lwwl_service01.util;

import org.apache.logging.log4j.util.Base64Util;
import org.bouncycastle.jce.provider.BouncyCastleProvider;//解密依赖

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Base64;

public class WechatDecryptUtil {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
/**
 * 解密微信加密数据
 * @param encryptedData 加密数据
 * @param sessionkey 会话密钥
 * @param iv 初始向量
 * @return 解密后的字符串
 */
    public static String decrypt(String encryptedData, String sessionkey,String iv){
        try{
            //Base64解码
            byte[] data = Base64.getDecoder().decode(encryptedData.getBytes());
            byte[] key = Base64.getDecoder().decode(sessionkey.getBytes());
            byte[] ivBytes = Base64.getDecoder().decode(iv.getBytes());
//            初始化密钥
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(ivBytes));
//            初始化密码
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            cipher.init(Cipher.DECRYPT_MODE,keySpec,params);
//            执行解密
            byte[] result = cipher.doFinal(data);
            return new String(result, "UTF-8");
        }catch (Exception e){
            throw new RuntimeException("解密失败",e);
        }
    }
}
